<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="学生姓名">
        <el-input v-model="formInline.studentname" placeholder="请输入学生姓名" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="danger" @click="onAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="编号"  />
      <el-table-column prop="studentname" label="姓名"  />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="address" label="家庭住址" />
      <el-table-column  label="操作" >
        <template #default="scope">
          <el-button type="primary" size="small" @click="onEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="onDel(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background
                   layout="total, prev, pager, next,jumper"
                   :total="total"
                   :page-count="pages"
                   :current-page="pageNum"
                   @current-change="changePageNum"
    />

    <el-dialog
        v-model="dialogVisible"
        title="学生信息"
        width="30%"
        :destroy-on-close="true"
    >

      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
      >
        <el-form-item label="学生姓名" prop="studentname">
          <el-input v-model="ruleForm.studentname" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio label="男" />
            <el-radio label="女" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="ruleForm.address" type="textarea" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="savaOrUpd">
            提交
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {reactive,toRefs,onMounted,getCurrentInstance} from 'vue'
import axios from 'axios'

import { ElMessage,ElMessageBox } from 'element-plus'

export default {
  name: "StuView",
  setup(){
    const {proxy}=getCurrentInstance()


    const data = reactive({
      dialogVisible:false,
      formInline:{
        studentname: ''
      },
      ruleForm:{
        studentname: '',
        gender:'',
        age:20,
        address: ''
      },
      rules:{
        studentname: [
          { required: true, message: '请输入学生名称', trigger: 'blur' },
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' },
        ],
        address: [
          { required: true, message: '请输入家庭地址', trigger: 'blur' },
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { pattern: /^(1[8-9]|[2-9]\d)$/,message: '请输入18-99的数字',trigger: 'blur' }
        ],
      },
      pageNum:1,
      tableData:[],
      total:0,
      pages:0,

    })

    const resetForm = () => {
      proxy.$refs['ruleFormRef'].resetFields();
    }
    const submitForm = () => {
      proxy.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {
          axios({
            url:'/api/student',
            method: 'get',
            data:data.ruleForm
          }).then(function (res){
            if(res.data.code==200){
              ElMessage.success("操作成功")

              data.dialogVisible=false
              getBackData()
            }else{
              ElMessage.error("出现异常")
            }
          })
        } else {
          ElMessage.error("请按提示填写表单")
          return false;
        }
      });
    }
    const changePageNum = (pageNo) => {
      data.pageNum=pageNo
      getBackData()
    }
    const savaOrUpd = () => {
      proxy.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {
          axios({
            method: 'post',
            url: '/api/student',
            data: data.ruleForm
          }).then(function (result){
            if(result.data.code=='200'){
              ElMessage.success("操作成功")
              data.dialogVisible=false
              getBackData()
            }else {
              ElMessage.error("操作失败")
            }
          })
        } else {
          ElMessage.error("请填写信息")
          return false;
        }
      });
    }
    const onDel = (id) => {
      ElMessageBox.confirm(
          '确定要删除该记录吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {

            axios({
              url:'/api/student/'+id,
              method:'delete'
            }).then(function (res){
              if(res.data.code==200){
                ElMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getBackData()
              }else{
                ElMessage({
                  type: 'error',
                  message: '删除失败',
                })
              }
            })

          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '取消操作',
            })
          })
    }
    const onEdit = (row) => {
      data.dialogVisible=true
      data.ruleForm=row
    }
    const onAdd = () => {
      data.ruleForm={
        studentname: '',
        gender:'',
        age:20,
        address: ''
      }
      data.dialogVisible=true
    }
    const onSubmit = () => {
      console.log('submit!')
      data.pageNum=1
      getBackData()

    }
    onMounted(function () {
      getBackData()
    })

    const getBackData = () => {
      axios({
        url: '/api/student?stuName='+data.formInline.studentname+'&pageNum='+data.pageNum,
        method:'get'
      }).then(function (res){
        console.log(res)
        data.tableData=res.data.data.records
        data.pageNum=res.data.data.current
        data.total=res.data.data.total
        data.pages=res.data.data.pages
      })
    }
    return {
      ...toRefs(data),
      onDel,
      onEdit,
      resetForm,
      submitForm,
      getBackData,
      onSubmit,
      onAdd,
      changePageNum,
      savaOrUpd
    }
  }
}
</script>